package unei.net.nio;

import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by sunlei on 2015/8/31.
 */
public class SelectorSelection {
    private final SelectorWorker worker;
    private final SelectorManager.Listener listener;
    private int interest;
    private SelectionKey key;
    private final AtomicBoolean closed = new AtomicBoolean();

    public SelectorSelection(final SelectorWorker worker, final AbstractSelectableChannel selectable, SelectorManager.Listener listener) throws ClosedChannelException {
        this.worker = worker;
        this.listener = listener;
        //注册操作，将Runnable加入到SelectWorker.ioTasks
        worker.addIoTask(new Runnable() {
            @Override
            public void run() {
                try {
                    SelectorSelection.this.key = selectable.register(worker.selector, 0, SelectorSelection.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 设置SelectionKey监听感兴趣的操作
     * @param ops
     */
    public void setInterestOps(int ops) {
        interest = ops;
    }

    /**
     * 使SelectionKey感兴趣的操作生效
     */
    public void enable() {
        worker.addIoTask(new Runnable() {
            @Override
            public void run() {
                try {
                    key.interestOps(interest);
                } catch (CancelledKeyException e) {
                }
            }
        });
    }

    /**
     * 使SelectionKey对所有的事件都失效
     */
    public void disable() {
        worker.addIoTask(new Runnable() {
            @Override
            public void run() {
                try {
                    key.interestOps(0);
                } catch (CancelledKeyException e) {
                }
            }
        });
    }

    /**
     * SelectionKey 取消
     */
    public void close() {
        if (closed.compareAndSet(false, true)) {
            worker.addIoTask(new Runnable() {
                @Override
                public void run() {
                    try {
                        key.cancel();
                    } catch (CancelledKeyException e) {
                    }
                    worker.release();
                }
            });
        }
    }

    /**
     * SelectionKey 触发select事件
     */
    public void onSelect() {
        listener.onSelect(this);
    }

    /**
     * 触发error事件
     * @param e
     */
    public void onError(Throwable e) {
        listener.onError(this, e);
    }
}
